#!/bin/sh

SUMFILE="SHA256SUM"
SUMPROG="sha256sum"

die()
{
	echo "$*" >&2
	exit 1
}

# Checksum directory ($1) contents
checksum_dir()
{
	local path="$1"

	[ -d "$path" ] || die "'$path' is not a directory"

	echo "entering directory '$path'"
	local olddir="$(pwd)"
	cd "$path" || die "cd '$path' failed"

	for file in *; do
		[ "$file" = "$SUMFILE" ] && {
			# Do not checksum the checksum file
			continue
		}
		[ -d "$file" ] && {
			# Recurse into subdirectory
			checksum_dir "$file"
			continue
		}
		[ -f "$file" ] || {
			# This is not a regular file. Don't checksum it.
			continue
		}
		[ -f "$SUMFILE" ] && {
			cat "$SUMFILE" | while read line; do
				if [ "x$file" = "x$(echo "$line" | cut -d' ' -f2- | cut -c2-)" ]; then
					# This file is already checksummed. Skip it.
					return 1
				fi
			done || continue
		}
		"$SUMPROG" -b "$file" >> "$SUMFILE" ||\
			die "checksumming of '$file' failed"
	done

	echo "leaving directory '$path'"
	cd "$olddir" || die "cd '$olddir' failed"
}

for path in "$@"; do
	checksum_dir "$path"
done
